package com.itheima.easy.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.itheima.easy.constant.TradingCacheConstant;
import com.itheima.easy.enums.TradingEnum;
import com.itheima.easy.exception.ProjectException;
import com.itheima.easy.handler.WapPayHandler;
import com.itheima.easy.utils.ExceptionsUtil;
import com.itheima.easy.vo.TradingVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName WapPayController.java
 * @Description 手机网页支付
 */
@Slf4j
@RequestMapping("trade-wap-feign")
@RestController
@Api(tags = "手机网页支付feign-controller")
public class WapPayController {

    @Autowired
    WapPayHandler wechatWapPayHandler;

    @Autowired
    RedissonClient redissonClient;

    /***
     * @description 生成交易表单，渲染后自动跳转支付宝或者微信引导用户完成支付
     * @param tradingVo 订单单
     * @return  TradingVo对象中的placeOrderJson：阿里云form表单字符串、微信prepay_id标识
     */
    @PostMapping("wap-trading")
    @ApiOperation(value = "手机网页支付",notes = "手机网页支付")
    @ApiImplicitParam(name = "tradingVo",value = "交易单",required = true,dataType = "TradingVo")
    @ApiOperationSupport(includeParameters ={"tradingVo.tradingOrderNo","tradingVo.returnUrl",
            "tradingVo.tradingAmount","tradingVo.quitUrl","tradingVo.tradingChannel",
            "tradingVo.openId","tradingVo.memo"})
    TradingVo wapTrading(@RequestBody TradingVo tradingVo){

        //1、对交易订单加锁
        Long productOrderNo = tradingVo.getProductOrderNo();
        String key = TradingCacheConstant.CREATE_PAY + productOrderNo;
        RLock lock = redissonClient.getFairLock(key);
        try {
            if (lock.tryLock(TradingCacheConstant.REDIS_WAIT_TIME, TimeUnit.SECONDS)){
                return wechatWapPayHandler.wapTrading(tradingVo);
            }else {
                throw new ProjectException(TradingEnum.PAYING_TRADING_FAIL);
            }
        } catch (Exception e) {
            log.error("统一收单线下交易预创建异常:{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(TradingEnum.PAYING_TRADING_FAIL);
        }finally {
            //释放锁
            lock.unlock();
        }
    }
}
